package com.webfileupload.servlets;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadServlet extends HttpServlet {

	private static final long serialVersionUID = 3456836507997033439L;
	private ServletContext sc;
	private String savePath;
	private String filename;
	private String uploaduname;
	
	public void init(ServletConfig config) {
		this.savePath = config.getInitParameter("savePath");
		this.sc = config.getServletContext();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		int flag = upload(request, response);
		if (flag == 1) {
			saveToDB(request, response);
		}
	}

	@SuppressWarnings("rawtypes")
	public int upload(HttpServletRequest request, HttpServletResponse response) {
		int flag = 0;
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List items = upload.parseRequest(request);
			Iterator it = items.iterator();
			while (it.hasNext()) {
				FileItem item = (FileItem) it.next();// FileItem可以包含文件或文本信息
				if (item.isFormField()) {// 判断是否是文本信息
					if (item.getFieldName().equals("name")) {
						uploaduname = item.getString("utf-8");
					}
					System.out.println("表单的参数名称：" + item.getFieldName()
							+ "，对应的参数值： " + item.getString("utf-8"));
				} else {
					if (item.getName() != null && !item.getName().equals("")) {
						System.out.println("上传文件的大小：" + item.getSize());
						System.out.println("上传文件的类型：" + item.getContentType());
						System.out.println("上传文件的名称：" + item.getName());
						File tempFile = new File(item.getName());
						filename = tempFile.getName();
						File file = new File(sc.getRealPath("/")+ "/" + savePath,
								filename);// 当前应用的真实物理路经
						System.out.println("sc.getRealPath()="
								+ sc.getRealPath("/"));
						item.write(file);
						request.setAttribute("upload.message", "上传文件成功！");
						flag = 1;
					} else {
						request.setAttribute("upload.message", "没有选择上传文件！");
						flag = 0;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("upload.message", "上传文件失败！");
			flag = 0;
		}
		try {
			request.getRequestDispatcher("/uploadResult.jsp").forward(request,
					response);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return flag;
	}

	public boolean saveToDB(HttpServletRequest request, HttpServletResponse response) {
		boolean f = false;
		if (filename != null || !filename.equals("")) {
			String url = "jdbc:mysql://localhost/test_web";
			String username = "dong";
			String password = "xiaodong";
			String sql = "insert into jsp04_fileupload(filename,username,time) values(?,?,?)";
			try {
				Class.forName("com.mysql.jdbc.Driver").newInstance();
				Connection conn = DriverManager.getConnection(url, username, password);
				PreparedStatement pstm = conn.prepareStatement(sql);
				pstm.setString(1, filename);
				pstm.setString(2, uploaduname);
				Date date = new Date();
				SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				pstm.setString(3, sfd.format(date));
				pstm.executeUpdate();
				pstm.close();
				conn.close();
				request.setAttribute("upload.dbmessage", "存入数据库成功！");
			} catch (Exception e) {
				e.printStackTrace();
				request.setAttribute("upload.dbmessage", "存入数据库失败！");
			}
		}
		return f;
	}

}
